#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
魔兽争霸3自动对战AI系统主程序

该脚本整合了视觉处理、游戏控制、AI决策等模块，
实现完整的自动对战功能。
"""

import time
import logging
import argparse
from src.ui.vision_processor import VisionProcessor
from src.game.controller import GameController
from src.ai.decision_maker import DecisionMaker


def setup_logging():
    """设置日志配置"""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler('data/logs/warcraft_ai.log', encoding='utf-8'),
            logging.StreamHandler()
        ]
    )
    return logging.getLogger(__name__)


def main(use_llm=False, llm_api_url=None, llm_api_key=None):
    """主函数"""
    logger = setup_logging()
    logger.info("魔兽争霸3自动对战AI系统启动")
    
    try:
        # 初始化各模块
        logger.info("初始化视觉处理模块...")
        vision = VisionProcessor()
        
        logger.info("初始化游戏控制模块...")
        controller = GameController()
        
        logger.info("初始化AI决策模块...")
        ai = DecisionMaker(
            use_llm=use_llm,
            llm_api_url=llm_api_url,
            llm_api_key=llm_api_key
        )
        
        logger.info("所有模块初始化完成")
        logger.info(f"大模型辅助决策: {'启用' if use_llm else '未启用'}")
        logger.info("请确保魔兽争霸3游戏已启动并处于主界面")
        logger.info("按 Ctrl+C 停止程序运行")
        
        # 主循环
        while True:
            try:
                # 1. 捕获并分析游戏画面
                logger.info("捕获游戏画面...")
                game_state = vision.analyze_game_state()
                logger.info(f"当前游戏状态: {game_state}")
                
                # 2. AI制定决策
                logger.info("AI制定决策...")
                decision = ai.make_decision(game_state)
                logger.info(f"AI决策: {decision}")
                
                # 3. 执行操作（示例实现，实际需要根据决策内容完善）
                # 注意：这里只是示例，实际需要根据decision的具体内容实现相应的控制逻辑
                if decision.get('action'):
                    action = decision['action']
                    action_type = action.get('type', 'idle')
                    
                    if action_type == 'move' and 'params' in action:
                        x = action['params'].get('x', 0)
                        y = action['params'].get('y', 0)
                        logger.info(f"移动鼠标到 ({x}, {y})")
                        # controller.move_mouse(x, y)  # 实际使用时取消注释
                        # controller.click(x, y)       # 实际使用时取消注释
                    
                    elif action_type == 'build' and 'params' in action:
                        structure = action['params'].get('structure', '')
                        x = action['params'].get('x', 0)
                        y = action['params'].get('y', 0)
                        logger.info(f"建造 {structure} 在 ({x}, {y})")
                        # 实现建造逻辑
                    
                    elif action_type == 'train' and 'params' in action:
                        unit = action['params'].get('unit', '')
                        logger.info(f"训练单位: {unit}")
                        # 实现训练逻辑
                    
                    elif action_type == 'attack' and 'params' in action:
                        x = action['params'].get('x', 0)
                        y = action['params'].get('y', 0)
                        logger.info(f"攻击位置 ({x}, {y})")
                        # 实现攻击逻辑
                    
                    else:
                        logger.info(f"执行动作: {action_type}")
                
                # 控制循环频率
                time.sleep(2)  # 2秒间隔
                
            except KeyboardInterrupt:
                logger.info("用户中断程序运行")
                break
            except Exception as e:
                logger.error(f"运行出错: {e}")
                time.sleep(5)  # 出错后等待5秒继续
    
    except Exception as e:
        logger.error(f"系统初始化失败: {e}")
        return False
    
    logger.info("魔兽争霸3自动对战AI系统停止运行")
    return True


if __name__ == "__main__":
    # 解析命令行参数
    parser = argparse.ArgumentParser(description='魔兽争霸3自动对战AI系统')
    parser.add_argument('--use-llm', action='store_true', 
                        help='启用大语言模型辅助决策')
    parser.add_argument('--llm-api-url', type=str, 
                        default='http://localhost:8000/v1/completions',
                        help='大语言模型API地址')
    parser.add_argument('--llm-api-key', type=str, default='',
                        help='大语言模型API密钥')
    
    args = parser.parse_args()
    
    # 运行主程序
    main(
        use_llm=args.use_llm,
        llm_api_url=args.llm_api_url,
        llm_api_key=args.llm_api_key
    )